import datetime
import json

from flask import Flask, request

from db.db_help import DBHelp
from model.base_model import MyBaseModel

app = Flask(__name__)


class BlogServer:
    # 获取博客列表
    @classmethod
    def getBlogs(cls):
        rows = DBHelp.selectRows("select * from blog", [])
        if len(rows) > 0:
            return MyBaseModel(code=200, msg="获取博客列表成功", data=rows)
        return MyBaseModel(code=500, msg=f"获取博客列表失败sba")

    # 获取博客详情
    @classmethod
    def getBlogDetails(cls, ):
        rows = DBHelp.selectRows("select * from blog where id=%s", [request.args.get("blogId"), ], )
        if len(rows) > 0:
            return MyBaseModel(code=200, msg="获取博客详情成功", data=rows[0])
        return MyBaseModel(code=500, msg=f"不存在此ID博客")

    # 删除博客
    @classmethod
    def deleteBlog(cls):
        rows = DBHelp.selectRows("delete from blog where id=%s", [request.args.get("blogId")])
        if len(rows) > 0:
            return MyBaseModel(code=200, msg="删除博客成功")
        return MyBaseModel(code=500, msg=f"不存在此ID博客")

    # 新增编辑博客
    @classmethod
    def editBlog(cls):
        if request.method == "POST":
            data = json.loads(request.data)
            id = DBHelp.insertRow(
                table="blog",
                column=[
                    'title',
                    'blog_type',
                    'content',
                    'createUser',
                    'createTime',
                    'homeImage'
                ],
                values=[
                    data['title'],
                    data['blog_type'],
                    data['content'],
                    data['createUser'],
                    datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                    data['homeImage']
                ],
            )
            if id != -1:
                return MyBaseModel(code=200, msg="插入博客成功", data=id)
            return MyBaseModel(code=500, msg="插入博客失败")
        else:
            sql = """
                UPDATE blog 
                SET %s=%s 
                WHERE id=%s
            """
            rows = DBHelp.selectRows(
                sql,
                [
                    request.args.get('title'),
                    request.args.get('title'),
                    request.args.get('blogId')
                ],
            )
            if rows:
                return MyBaseModel(code=200, msg="更新博客成功", data=None)
            return MyBaseModel(code=500, msg="更新博客失败", data=None)
